<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import jdfkService from '@/api/jdfk'
import wjfwService from '@/api/wjfw'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FjxxQueryResult, Fj } from '@/api/jdfk-dto'
import wjzs from '@/components/wjzs.vue'
import { useMainStore } from '@/store/main'
const store = useMainStore()
const emit = defineEmits(['refresh'])
/*
 * 打开弹窗
 */
const dialogVisible = ref(false)
const currentRow = ref()
const openDialog = (row: any) => {
  dialogVisible.value = true
  currentRow.value = row
  queryFjxx()
}

/*
 * 获取附件列表
 */
const fjxxList = ref<FjxxQueryResult[]>([])
const queryFjxx = () => {
  const params = { jdbh: currentRow.value.jdbh }
  jdfkService.queryFjxx(params).then((res) => {
    fjxxList.value = res.data
  })
}

/*
 * 删除附件
 */
const batchDeleteFj = () => {
  ElMessageBox.confirm('是否删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const params = { fjbhList: multipleSelection.value.map((fj) => fj.fjbh) }
    jdfkService
      .deleteFjxx(params)
      .then(() => {
        ElMessage.success('删除成功')
        queryFjxx()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}
const closeDialog = () => {
  currentRow.value = undefined
  previewUrl.value = undefined
  dscFjList.value = []
  yscFjList.value = []
  emit('refresh')
}

const multipleSelection = ref<FjxxQueryResult[]>([])
const handleSelectionChange = (val: FjxxQueryResult[]) => {
  multipleSelection.value = val
}

/*
 * 上传附件
 */
const dscFjList = ref<any[]>([])
const yscFjList = ref<Fj[]>([])
const uploadFj = async (fj: any) => {
  const formData = new FormData()
  formData.append('file', fj.file)
  wjfwService.upload(formData).then((res) => {
    let wjkzm = ''
    const lastDotIndex = fj.file.name.lastIndexOf('.')
    if (lastDotIndex !== -1 && lastDotIndex !== 0) {
      wjkzm = fj.file.name.slice(lastDotIndex + 1)
    }
    yscFjList.value.push({
      fjbh: res.wjbh,
      fjmc: fj.file.name,
      wjkzm,
    })
    uploadSuccess()
  })
}
// 限制上传相同的文件
const beforeUpload = (file: any) => {
  if (
    yscFjList.value.find((fj) => fj.fjmc === file.name) ||
    fjxxList.value.find((fj) => fj.wjmc === file.name)
  ) {
    ElMessage.warning(`${file.name}已存在，请务重复上传`)
    return false
  }
  return true
}

const uploadSuccess = () => {
  if (dscFjList.value.every((fj) => fj.status === 'success')) {
    const params = {
      jdbh: currentRow.value.jdbh,
      fjList: yscFjList.value,
    }
    jdfkService
      .uploadFj(params)
      .then(() => {
        ElMessage.success('上传成功')
        queryFjxx()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  }
}

// 查看附件
const previewType = ref('')
const previewUrl = ref()
const wjzsRef = ref()
const viewFj = (row: any) => {
  const params = { wjbh: row.fjbh }
  wjfwService.downloadBlob(params).then((res) => {
    if (res.type === 'application/json') {
      const reader = new FileReader()
      reader.onload = () => {
        const jsonData =
          typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
        ElMessage({ type: 'warning', message: jsonData.message })
      }
      reader.readAsText(res)
    } else {
      previewUrl.value = window.URL.createObjectURL(res)
      previewType.value = row.wjkzm?.toLowerCase()
      if (previewType.value === 'pdf') {
        nextTick(() => {
          wjzsRef.value?.init()
        })
      }
    }
  })
}

const selectable = (row: any) => {
  return store.userInfo.ryid === row.scrbh
}
defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="附件信息"
    width="70%"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <div class="dialogcontent">
      <div class="left">
        <div class="tab-box">
          <el-tabs model-value="1">
            <el-tab-pane name="1" label="附件列表">
              <div style="height: calc(100% - 30px)">
                <el-table
                  :data="fjxxList"
                  height="100%"
                  row-key="fjbh"
                  @row-click="viewFj"
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" width="40" :selectable="selectable" />
                  <el-table-column prop="wjmc" label="附件名称" />
                </el-table>
              </div>
              <div class="action">
                <el-upload
                  class="fj-upload"
                  v-model:file-list="dscFjList"
                  :show-file-list="false"
                  multiple
                  :accept="'.pdf,.jpg,.jpeg,.png,.bmp'"
                  :http-request="uploadFj"
                  :before-upload="beforeUpload"
                >
                  <el-button size="small" type="success">选取文件</el-button>
                </el-upload>
                <el-link
                  :underline="false"
                  type="primary"
                  icon="Delete"
                  @click="batchDeleteFj"
                  :disabled="!multipleSelection.length"
                  >批量删除</el-link
                >
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div class="right">
        <div class="tab-box">
          <el-tabs model-value="1">
            <el-tab-pane name="1" label="附件展示">
              <wjzs v-if="previewType === 'pdf'" ref="wjzsRef" wjlx="pdf" :url="previewUrl" />
              <div v-else class="preview">
                <img :src="previewUrl" alt="" />
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="default" style="margin-left: 10px" @click="dialogVisible = false"
          >关闭</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialogcontent {
  height: 70vh;
  display: flex;
  .tab-box {
    height: 100%;
    :deep(.el-tabs__nav) {
      padding: 0 16px;
    }
    :deep(.el-tabs__content) {
      padding: 10px;
    }
    .action {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .preview {
      text-align: center;
      height: 100%;
      width: 100%;
      img {
        height: 100%;
      }
    }
  }
  .left {
    box-sizing: border-box;
    width: 325px;
    margin-right: 10px;
  }
  .right {
    width: calc(100% - 335px);
  }
}
</style>
